package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author fantuan
 * @created 2025/10/17 18:11
 * @description
 */
@Slf4j
@Aspect
@Component
public class RedisAspect {
    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.anno.Cacheable)")
    public void pt(){
    }

    @Around("pt()")
    public Object redis(ProceedingJoinPoint pjp) {

        Object returnValue = null;
        String key = null;
        long expireTime = 0;
        TimeUnit timeUnit = null;
        try {
            Class<?> targetClass = pjp.getTarget().getClass();
            String name = pjp.getSignature().getName();
            Method method = targetClass.getMethod(name);
            Cacheable cacheable = method.getAnnotation(Cacheable.class);
            key = cacheable.redisKeyPrefix() + name;
            expireTime = cacheable.redisKeyExpireTime();
            timeUnit = cacheable.redisKeyExpireTimeUnit();
            String jsonStr = redisClient.opsForValue().get(key);
            if(ObjectUtil.isNotEmpty(jsonStr)){
                returnValue = JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        }catch (Exception e){
            log.error("缓存异常{}", e.getMessage());
        }
        try {
            returnValue = pjp.proceed();
        }catch (Throwable throwable){
            log.error("您的操作有问题，请稍后重试:{}", throwable.getMessage());
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        try {
            redisClient.opsForValue().set(key, JSONUtil.toJsonStr(returnValue), expireTime, timeUnit);
        }catch (Exception e){
            log.error("缓存异常:{}", e.getMessage());
        }
        return returnValue;
    }

}

